//
//  GroupDetailViewController.m
//  FootPrint
//
//  Created by GeneChu on 4/12/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "GroupDetailViewController.h"
#import "FriendSelCell.h"
#import "FriendDetailViewController.h"
#import "EventDetailViewController.h"

@interface GroupDetailViewController ()

@end

@implementation GroupDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _parser = [[FriendParser alloc] init];
        _parser.gDelegate = self;
        
        _newMemberList = [[NSMutableArray alloc] initWithCapacity:2];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setEMode:eGroupModeModify];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    self.newMemberList = nil;
    [_parser release];
    [_groupMsg release];
    [_groupIcon release];
    [_groupName release];
    [_groupRealName release];
    [_groupMemberTable release];
    [_rightBtn release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setGroupIcon:nil];
    [self setGroupName:nil];
    [self setGroupRealName:nil];
    [self setGroupMemberTable:nil];
    [self setRightBtn:nil];
    [super viewDidUnload];
}

- (IBAction)exit:(id)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)activity:(id)sender
{
    if (_eMode == eGroupModeCreate) {
        if (_groupRealName.text.length == 0) {
            [[iToast makeText:@"名字不能为空"] show];
            return;
        }
        if (_newMemberList.count == 0) {
            [[iToast makeText:@"好友不能为空"] show];
            return;
        }
        [_parser createGroup:[GConfig getUserId] forName:_groupRealName.text withMembers:_newMemberList];

    } else {
        EventDetailViewController * detail = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
        
        UINavigationController * navVc = self.navigationController;
        if (nil == navVc) {
            navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
            navVc.navigationBarHidden = YES;
            [ROOT_VC presentModalViewController:navVc animated:YES];
        } else {
            [navVc pushViewController:detail animated:YES];
        }
        
        [detail createWithFriendList:[GToolUtil PBArr2NSArr:_groupMsg.users]];
    }
}

- (void)setEMode:(eGroupMode)eMode
{
    _eMode = eMode;
    
    if (_eMode == eGroupModeCreate) {
        _groupName.hidden = NO;
        _groupRealName.enabled = YES;
        [_rightBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_groupRealName becomeFirstResponder];
    } else {
        _groupName.hidden = YES;
        _groupRealName.enabled = NO;
        [_rightBtn setTitle:@"活动" forState:UIControlStateNormal];
        [_groupRealName resignFirstResponder];
    }
}

- (void)setGroupMsg:(GroupMessage *)groupMsg
{
    [_groupMsg release];
    _groupMsg = [groupMsg retain];
    
    self.newMemberList = [GToolUtil PBArr2NSArr:groupMsg.users];
    
    _groupRealName.text = _groupMsg.name;
    if (!_groupMsg.image.isSys) {
        [_groupIcon loadAsyncImage:_groupMsg.image.imageUrl];
    } else {
        [_groupIcon setSysImageWithId:_groupMsg.image.id];
    }
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _newMemberList.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"AddMerCell" owner:self options:nil];
		UITableViewCell* cell = (UITableViewCell*)[arr objectAtIndex:0];
        UILabel* label = (UILabel*)[cell viewWithTag: 2];
        [label setText:@"添加组成员"];
        
        return cell;
    }
    static NSString *friendSelCellIdentifier = @"friendSelCellIdentifier";
    FriendSelCell *cell = [tableView dequeueReusableCellWithIdentifier:friendSelCellIdentifier];
    if (cell == nil) {
        cell = [[[FriendSelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendSelCellIdentifier] autorelease];
    }
 
    UserMessage * msg = [_newMemberList objectAtIndex: (indexPath.row)-1];
    [cell updateUserMsg:msg];

    cell.redioImage.hidden = YES;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.row == 0){
        FriendSelViewController * selVC = [[[FriendSelViewController alloc] initWithNibName:@"FriendSelViewController" bundle:nil] autorelease];
        
        NSMutableArray * selIds = [NSMutableArray arrayWithCapacity:_groupMsg.users.count];
        for (int i = 0; i < _newMemberList.count; i++) {
            UserMessage * user = [_newMemberList objectAtIndex:i];
            [selIds addObject:[NSNumber numberWithLongLong:user.id]];
        }
        selVC.selFriends = selIds;
        selVC.selDelegate = self;
        [self.navigationController pushViewController:selVC animated:YES];
        
        selVC.segmentControl.hidden = YES;
        return;
    }
    
    FriendDetailViewController * detail = [[[FriendDetailViewController alloc] initWithNibName:@"FriendDetailViewController" bundle:nil] autorelease];
    
    UINavigationController * navVc = self.navigationController;
    if (nil == navVc) {
        navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
        navVc.navigationBarHidden = YES;
        [ROOT_VC presentModalViewController:navVc animated:YES];
    } else {
        [navVc pushViewController:detail animated:YES];
    }
    detail.activityBtn.hidden = YES;
    detail.btnDegree.hidden = YES;
    detail.btnDisagree.hidden = YES;
    [detail updateUserStatus:[_newMemberList objectAtIndex:(indexPath.row)-1]];
}


#pragma mark - GroupDelegate

- (void) didAddGroupFriends:(GroupFriendAddResponseMessage*)friends {
    if (friends && friends.resultCode == 0) {
        [[iToast makeText:@"修改成功"] show];
    } else {
        //[[iToast makeText:@"修改失败"] show];
    }
}

- (void) didRemoveGroupFriends:(GroupFriendRemoveResponseMessage*)friends {
    if (friends && friends.resultCode == 0) {
        [[iToast makeText:@"修改成功"] show];
    } else {
        //[[iToast makeText:@"修改失败"] show];
    }
}

- (void) didCreateGroup:(GroupCreateResponseMessage*)result
{
    if (result && result.resultCode == 0) {
        [FriendManager sharedInstance].isLatestGroup = NO;
        [[iToast makeText:@"创建成功"] show];
        [self exit:nil];
    } else {
        [[iToast makeText:@"创建失败"] show];
    }
}


#pragma mark - FriendSelDelegate

- (BOOL)willUpdateFriendSel:(NSMutableArray*)newSelFriends groupSel:(NSMutableArray*)selGroup
{
    if (newSelFriends.count == 0) {
        [[iToast makeText:@"至少选择一个好友"] show];
        return NO;
    }
    return YES;
}

- (void)didUpdateFriendSel:(NSMutableArray*)newSelFriends groupSel:(NSMutableArray*)selGroup
{
    [_newMemberList removeAllObjects];
    
    NSMutableSet * newSet = [NSMutableSet setWithCapacity:newSelFriends.count];
    for (EventMessage_UserStatus * status in newSelFriends) {
        [newSet addObject:[NSNumber numberWithLongLong:status.user.id]];
        [_newMemberList addObject:status.user];
    }
    
    NSMutableSet * oldSet = [NSMutableSet setWithCapacity:_groupMsg.users.count];
    for (int i = 0; i < _groupMsg.users.count; i++) {
        UserMessage * msg = [_groupMsg usersAtIndex:i];
        [oldSet addObject:[NSNumber numberWithLongLong:msg.id]];
    }

    NSMutableArray * addIds = [NSMutableArray arrayWithCapacity:2];
    for (EventMessage_UserStatus * status in newSelFriends) {
        if (![oldSet containsObject:[NSNumber numberWithLongLong:status.user.id]]) {
            [addIds addObject:[NSNumber numberWithLongLong:status.user.id]];
        }
    }
    
    NSMutableArray * removeIds = [NSMutableArray arrayWithCapacity:2];
    for (int i = 0; i < _groupMsg.users.count; i++) {
        UserMessage * msg = [_groupMsg usersAtIndex:i];
        if (![newSet containsObject:[NSNumber numberWithLongLong:msg.id]]) {
            [removeIds addObject:[NSNumber numberWithLongLong:msg.id]];
        }
    }
    
    [_groupMemberTable reloadData];
    
    if (addIds.count > 0) {
        [_parser addGroupMember:_groupMsg.id withMemberList:addIds];
    }
    if (removeIds.count > 0) {
        [_parser removeGroupMember:_groupMsg.id withMemberList:removeIds];
    }
    
}


#pragma mark - UITextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length == 0) {
        [[iToast makeText:@"名字不能为空"] show];
        return NO;
    }
    [textField resignFirstResponder];
    return YES;
}

@end
